package com.ycsj.goldmedalnewconcept.main.activity;

import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.NonNull;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.SpKeys;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.SnackbarUtil;
import com.ycsj.common.utils.StateBarUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.util.PermissionUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.autosize.internal.CancelAdapt;

/**
 * 角色选择界面
 * Created by Administrator on 2018/4/17 0017.
 */
public class ChooseRoleActivity extends BaseActivity implements View.OnClickListener, CancelAdapt {
    @BindView(R.id.ll_main)
    LinearLayout llMain;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ll_student)
    LinearLayout llStudent;
    @BindView(R.id.ll_teacher)
    LinearLayout llTeacher;
    @BindView(R.id.ll_parent)
    LinearLayout llParent;
    @BindView(R.id.ll_master)
    LinearLayout llMaster;
    @BindView(R.id.bt_OK)
    Button btOK;
    @BindView(R.id.lv_student)
    ImageView lvStudent;
    @BindView(R.id.lv_parent)
    ImageView lvParent;
    @BindView(R.id.lv_teacher)
    ImageView lvTeacher;
    @BindView(R.id.lv_master)
    ImageView lvMaster;


    //显示已选择学生的TextView
    @BindView(R.id.tv_show_student)
    TextView tvShowStudent;
    //显示已选择老师的TextView
    @BindView(R.id.tv_show_teacher)
    TextView tvShowTeacher;
    //显示已选择家长的TextView
    @BindView(R.id.tv_show_parent)
    TextView tvShowParent;
    //显示已选择校长的TextView
    @BindView(R.id.tv_show_master)
    TextView tvShowMaster;

    //用于存放提示的TextView的集合
    private List<TextView> textViews;

    //记录选择的角色类型,0学生,1家长,2老师,3校长
    private int type = -1;

    @Override
    protected int getContentLayout() {
        return R.layout.main_activity_choose_role;
    }

    @Override
    protected void init() {

        //沉浸状态栏
        StateBarUtil.customImmerseBar(this);

        //初始化视图
        initView();

        //检查更新
//        AppUpdateUtil.updateVersion(this);

        //隐私服务协议
        startDialog();
    }


    /**
     * 初始化视图的方法
     */
    private void initView() {
        ivBack.setVisibility(View.INVISIBLE);
        tvTitle.setText("选择角色");
        btOK.setEnabled(false);
        textViews = new ArrayList<>();
        textViews.add(tvShowStudent);
        textViews.add(tvShowParent);
        textViews.add(tvShowTeacher);
        textViews.add(tvShowMaster);
    }

    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @OnClick({R.id.lv_student, R.id.lv_parent, R.id.lv_teacher, R.id.lv_master, R.id.bt_OK})
    public void onClick(View view) {
        if (!isDoubleClick(view)) {


//        if (SPUtil.getBoolean(ChooseRoleActivity.this, "hasAgree")) {
            int id = view.getId();
            if (id == R.id.lv_student) {
                //学生
                syncState(0);
                lvStudent.setImageResource(R.drawable.main_student_select);
                lvParent.setImageResource(R.drawable.main_parent_normal);
                lvTeacher.setImageResource(R.drawable.main_teacher_normal);
                lvMaster.setImageResource(R.drawable.main_master_normal);
            } else if (id == R.id.lv_parent) {
                //家长
                syncState(1);
                lvStudent.setImageResource(R.drawable.main_student_normal);
                lvParent.setImageResource(R.drawable.main_parent_select);
                lvTeacher.setImageResource(R.drawable.main_teacher_normal);
                lvMaster.setImageResource(R.drawable.main_master_normal);
            } else if (id == R.id.lv_teacher) {
                //老师
                syncState(2);
                lvStudent.setImageResource(R.drawable.main_student_normal);
                lvParent.setImageResource(R.drawable.main_parent_normal);
                lvTeacher.setImageResource(R.drawable.main_teacher_select);
                lvMaster.setImageResource(R.drawable.main_master_normal);
            } else if (id == R.id.lv_master) {
                //校长
                syncState(3);
                lvStudent.setImageResource(R.drawable.main_student_normal);
                lvParent.setImageResource(R.drawable.main_parent_normal);
                lvTeacher.setImageResource(R.drawable.main_teacher_normal);
                lvMaster.setImageResource(R.drawable.main_master_select);
            } else if (id == R.id.bt_OK) {
                //确定按钮
                goToMainAction();
            }
//        } else {
//            ToastUtils.show("您未同意用户协议与隐私政策,不能进行任何操作,请重新启动App后操作");
//        }
        }
    }

    /**
     * 根据选择的角色跳转到不同模块的主界面的方法
     */
    private void goToMainAction() {
        if (type == -1) {
            //证明还没选择就角色
            SnackbarUtil.ShortSnackbar(llMain, "您还没有选择角色", 0).show();
            return;
        } else {
            //证明选择了角色,跳转到登录界面
            UiUtils.startActivity(this, LoginActivity.class);
            finish();
        }
    }


    /**
     * 根据选择的位置控制提示的隐藏与显示
     *
     * @param pos
     */
    private void syncState(int pos) {
        if (!btOK.isEnabled()) {
            btOK.setEnabled(true);
            btOK.setBackgroundResource(R.drawable.main_bt_ok);
        }

        for (int i = 0; i < textViews.size(); i++) {
            if (pos == i) {
                textViews.get(i).setVisibility(View.VISIBLE);
                type = i;
            } else {
                textViews.get(i).setVisibility(View.INVISIBLE);
            }
        }

        if (type == 0) {
            // 保存学生
            SPUtil.put(this, SpKeys.ROLETYPE, "0");
        } else if (type == 1) {
            //保存家长角色
            SPUtil.put(this, SpKeys.ROLETYPE, "1");
        } else if (type == 2) {
            //保存老师角色
            SPUtil.put(this, SpKeys.ROLETYPE, "2");
        } else if (type == 3) {
            //保存校长角色
            SPUtil.put(this, SpKeys.ROLETYPE, "3");
        }
    }

    /**
     * 用户协议与隐私政策的弹窗
     */
    private void startDialog() {
        if (!SPUtil.getBoolean(ChooseRoleActivity.this, "hasAgree")) {


            final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.show();
            alertDialog.setCancelable(false);
            Window window = alertDialog.getWindow();
            if (window != null) {
                window.setContentView(R.layout.dialog_initmate);
                window.setGravity(Gravity.CENTER);

                TextView tvContent = window.findViewById(R.id.tv_content);
                TextView tvCancel = window.findViewById(R.id.tv_cancel);
                TextView tvAgree = window.findViewById(R.id.tv_agree);
//                String str = "    感谢&#160;&#160;您对本公司的支持!本公司非常重视您的个人信息和隐私保护。" +
//                        "为了更好地保障您的个人权益，在您使用我们的产品前，" +
//                        "请务必审慎阅读《隐私政策》和《用户协议》内的所有条款，" +
//                        "尤其是:\n" +
//                        " 1.我们对您的个人信息的收集/保存/使用/对外提供/保护等规则条款，以及您的用户权利等条款;\n" +
//                        " 2. 约定我们的限制责任、免责条款;\n" +
//                        " 3.其他以颜色或加粗进行标识的重要条款。\n" +
//                        "如您对以上协议有任何疑问，" +
//                        "可通过人工客服或发邮件至sharetronicios@163.com与我们联系。您点击“同意并继续”的行为即表示您已阅读完毕并同意以上协议的全部内容。" +
//                        "如您同意以上协议内容，请点击“同意”，开始使用我们的产品和服务!";
                String str = getResources().getString(R.string.yhxy_yszc);

                SpannableStringBuilder ssb = new SpannableStringBuilder();
                ssb.append(str);
                final int start = str.indexOf("《");//第一个出现的位置
                ssb.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        if (!isDoubleClick(widget)) {
                            AgreementAndPrivacyActivity.goActivity(ChooseRoleActivity.this, "隐私政策");
                        }
                    }

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setUnderlineText(false);
                        ds.setColor(Color.BLUE);
                    }
                }, start, start + 6, 0);

                int end = str.lastIndexOf("《");
                ssb.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        if (!isDoubleClick(widget)) {
                            AgreementAndPrivacyActivity.goActivity(ChooseRoleActivity.this, "用户协议");
                        }
                    }

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setUnderlineText(false);
                        ds.setColor(Color.BLUE);
                    }
                }, end, end + 6, 0);

                tvContent.setMovementMethod(LinkMovementMethod.getInstance());
                tvContent.setText(ssb, TextView.BufferType.SPANNABLE);


                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.cancel();
//                        finish();
                    }
                });

                tvAgree.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //用户点击同意后在SP中保存一个变量值
                        SPUtil.put(ChooseRoleActivity.this, "hasAgree", true);
                        alertDialog.cancel();

                        //申请权限的操作
                        doObtainPermission();
                    }
                });
            }

        }
    }


    /**
     * 申请权限
     */
    private void doObtainPermission() {

        if (Build.VERSION.SDK_INT >= 23 && PermissionUtil.checkPermission(ChooseRoleActivity.this, PermissionUtil.PERMISSIONS_STORAGE).length > 0) {
            PermissionUtil.checkAndRequestPermissions(ChooseRoleActivity.this, PermissionUtil.PERMISSIONS_STORAGE);
        }
    }

    /**
     * 申请权限的回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDenin = false;
//        LogUtils.iTag("test", grantResults);

        if (requestCode == PermissionUtil.REQUEST_CODE) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDenin = true;
                    break;
                }
            }
            if (hasPermissionDenin) {
//                ToastUtils.showShort("未同意所有权限将无法使用相关功能");
            }
        }
    }

}
